//
//  QuotedPriceViewController.swift
//  jiaoyi
//  我的报价
//  Created by 易万军 on 2018/10/21.
//  Copyright © 2018 wjk. All rights reserved.
//

import UIKit
import SwiftyJSON
import MJRefresh

class QuotedPriceViewController: UIViewController,UISearchBarDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    
    var data:[[JSON]] = [[JSON]]()
    
    @IBOutlet weak var searchBar: UISearchBar!
    @IBOutlet weak var filterButton: UIButton!
    @IBOutlet weak var cancelButton: UIButton!
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var viewFilter: UIView!
    var dataArray: [JSON] = [JSON]()
    
    var status:Int = 0
    
    var page:Int = 1
    
    var variety_id:Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.viewFilter.isHidden = true
        self.searchBar.delegate = self
        tableView.register(UINib.init(nibName: "QuotedPriceTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        tableView.rowHeight = 229
        tableView.backgroundColor = UIColor.groupTableViewBackground
        tableView.separatorColor = UIColor.red
        tableView.separatorStyle = .none
        // Do any additional setup after loading the view.
        let textFieldInsideSearchBar = searchBar.value(forKey: "searchField")as? UITextField
        
        textFieldInsideSearchBar?.textColor = UIColor.white
        
        let textFieldInsideSearchBarLabel = textFieldInsideSearchBar!.value(forKey: "placeholderLabel")as? UILabel
        
        textFieldInsideSearchBarLabel?.textColor = UIColor.white
        self.collectionView.register(R.nib.rightCollectionViewCell(), forCellWithReuseIdentifier: "RightCollectionViewCell")
        self.collectionView.register(RightHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "RightHeader")
        loadData()
        addRightBar()
        
        tableView.mj_header = MJRefreshNormalHeader{ [weak self] in
            self?.page = 1
            self?.loadData()
        }
        
        tableView.mj_footer = MJRefreshAutoFooter {[weak self] in
            
            
            self?.loadData()
            
        }
        
        
        
    }
    
    
    func addRightBar() {
        let bar = UIBarButtonItem(image: UIImage(named: "fliter_icon"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.openMessage(_:)))
        self.navigationItem.rightBarButtonItem = bar
        
    }
    
    @objc func openMessage(_ bar : UIBarButtonItem) {
        self.viewFilter.isHidden = !self.viewFilter.isHidden
        self.view.endEditing(true)
    }
    
    @IBAction func hidden(_ sender: UIButton) {
        self.viewFilter.isHidden = true
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        self.page = 1
        self.loadData()
        self.view.endEditing(true)
    }
    
    
    func loadData() -> Void {
        if title == "我的报价" {
            NetWorkRequest(.myoffer(alias: searchBar.text!,status: "\(status)",variety_id: "\(variety_id)",page:"\(self.page)")) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    let data = jsonFormater(data: res["data"] as Any)
                    if self.page <= 1 {
                        self.dataArray.removeAll()
                    }
                    let arr = jsonFormater(data: jsonFormater(data: res["data"] as Any)["offers"].dictionaryValue)["data"].arrayValue
                    arr.forEach({ (d) in
                        self.dataArray.append(d)
                    })
                    self.page += 1
                    self.tableView.reloadData()
                    
                    self.tableView.mj_header.endRefreshing()
                    self.tableView.mj_footer.endRefreshing()
                    if arr.count <= 0 {
                        self.tableView.mj_footer.isHidden = true
                    }else {
                        self.tableView.mj_footer.isHidden = false
                    }
                    
                    self.data.removeAll()
                    
                    var ar:[JSON] = [JSON]()
                    ar.append(jsonFormater(data: ["id":"1","name":"正常"]))
                    ar.append(jsonFormater(data: ["id":"2","name":"成功"]))
                    ar.append(jsonFormater(data: ["id":"3","name":"失效"]))
                    
//                    self.data.append(ar)
                    
                    var ar2:[JSON] = [JSON]()
                    
                    data["options"].dictionaryValue["varieties"]?.arrayValue.forEach({ (j) in
                        ar2.append(j)
                    })
                    self.data.append(ar2)
                    self.data.append(ar)
                    self.collectionView.reloadData()
                    
                }
            }
        }else {
            NetWorkRequest(.myofferee(alias: searchBar.text!,status: "\(status)",variety_id: "\(variety_id)",page:"\(self.page)")) { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    let data = jsonFormater(data: res["data"] as Any)
                    
                    if self.page <= 1 {
                        self.dataArray.removeAll()
                    }
                    let arr = jsonFormater(data: jsonFormater(data: res["data"] as Any)["offers"].dictionaryValue)["data"].arrayValue
                    arr.forEach({ (d) in
                        self.dataArray.append(d)
                    })
                    self.page += 1
                    self.tableView.reloadData()
                    self.data.removeAll()
                    
                    var ar:[JSON] = [JSON]()
                    ar.append(jsonFormater(data: ["id":"1","name":"正常"]))
                    ar.append(jsonFormater(data: ["id":"2","name":"成功"]))
                    ar.append(jsonFormater(data: ["id":"3","name":"失效"]))
                    
                    
                    
                    var ar2:[JSON] = [JSON]()
                    
                    data["options"].dictionaryValue["varieties"]?.arrayValue.forEach({ (j) in
                        ar2.append(j)
                    })
                    self.data.append(ar2)
                    self.data.append(ar)
                    self.collectionView.reloadData()
                    self.tableView.mj_header.endRefreshing()
                    self.tableView.mj_footer.endRefreshing()
                    if arr.count <= 0 {
                        self.tableView.mj_footer.isHidden = true
                    }else {
                        self.tableView.mj_footer.isHidden = false
                    }
                }
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @IBAction func filterButtonAction(_ sender: Any) {
        self.viewFilter.isHidden = true
        self.tableView.mj_header.beginRefreshing()
    }
    
    @IBAction func cancelButtonAction(_ sender: Any) {
        status = 0
        variety_id = 0
        searchBar.text = ""
        self.tableView.mj_header.beginRefreshing()
        self.viewFilter.isHidden = true
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: deviceWidth(), height: 30)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: collectionView.bounds.size.width/3, height: 80)
    }
    
    //设定header和footer的方法，根据kind不同进行不同的判断即可
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionElementKindSectionHeader{
            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "RightHeader", for: indexPath) as! RightHeader
            if indexPath.section == 0 {
                headerView.label.text = "品种"
            }else {
                headerView.label.text = "状态"
            }
            
            return headerView
        }
        return UICollectionReusableView()
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return data.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data[section].count
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RightCollectionViewCell", for: indexPath) as! RightCollectionViewCell
        
        let j = data[indexPath.section][indexPath.row]
        
        cell.btn.setTitle(j["name"].stringValue, for: .normal)
        cell.btn.setTitleColor(kRGBColorFromHex(rgbValue: 0x333333), for: .normal)
        cell.btn.backgroundColor = kRGBColorFromHex(rgbValue: 0xf3f3f3)
        
        viewRadius(cor: 5, img: cell.btn)
        
        
        
        if indexPath.section == 0 {
            if j["id"].intValue == variety_id {
                cell.btn.setTitleColor(kRGBColorFromHex(rgbValue: 0x50a3f8), for: .normal)
                viewBorderRadius(cor: 5, img: cell.btn, with: 1, color: kRGBColorFromHex(rgbValue: 0x50a3f8))
                cell.btn.backgroundColor = kRGBColorFromHex(rgbValue: 0xedf7ff)
            }
        }else {
            if j["id"].intValue == status {
                cell.btn.setTitleColor(kRGBColorFromHex(rgbValue: 0x50a3f8), for: .normal)
                viewBorderRadius(cor: 5, img: cell.btn, with: 1, color: kRGBColorFromHex(rgbValue: 0x50a3f8))
                cell.btn.backgroundColor = kRGBColorFromHex(rgbValue: 0xedf7ff)
            }
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            variety_id = data[0][indexPath.row]["id"].intValue
        }else {
            status = data[1][indexPath.row]["id"].intValue
        }
        collectionView.reloadData()
    }
    
}

extension QuotedPriceViewController: UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
//        return 10
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuotedPriceTableViewCell
        cell.selectionStyle = .none
        let dic = jsonFormater(data: self.dataArray[indexPath.row])
        
        cell.labelNo.text = dic["alias"].stringValue
        
        if dic["status_text"].stringValue == "正常" {
            cell.labelStatus.textColor = kRGBColorFromHex(rgbValue: 0x628ecd)
        }else if dic["status_text"].stringValue == "失效" {
            cell.labelStatus.textColor = kRGBColorFromHex(rgbValue: 0xff836f)
        }else {
            cell.labelStatus.textColor = kRGBColorFromHex(rgbValue: 0x3eb072)
        }
        
        cell.labelStatus.text = dic["status_text"].stringValue
        
        cell.labelPin.text = dic["variety_name"].stringValue
        
        cell.labelCount.text = dic["num"].stringValue
        cell.labelMPrice.text = "\(dic["price"].floatValue / 100)"
        
        cell.labelAddressDep.text = dic["depot_name"].stringValue
        cell.labelJiaoHuo.text = dic["delivery_point"].stringValue
        cell.labelDate.text = dic["published_at"].stringValue
        cell.btnNew.isHidden = !dic["is_offer"].boolValue
        if title == "我的被报价" {
            cell.btnNew.setTitle("确价", for: .normal)
            cell.btnCancel.isHidden = true
            if dic["status_text"].stringValue == "失效" || dic["status_text"].stringValue == "成功" {
                cell.btnNew.isHidden = true
            }else {
                cell.btnNew.isHidden = false
            }
        }else {
            cell.btnCancel.isHidden = !dic["is_cancel_offer"].boolValue
        }
        
        
        
        
        
        cell.cancleButtonBlock = { () in
            NetWorkRequest(.bidingCancel(id: dic["id"].stringValue), completion: { (res) -> (Void) in
                if res["code"] as! String == "000000" {
                    showMessage(message: "操作成功")
                    self.tableView.mj_header.beginRefreshing()
                }
            })
        }
        cell.newButtonBlock = {[weak self]() in
            if self?.title == "我的被报价" {//应价
                
                NetWorkRequest(.receiving(id: dic["id"].stringValue), completion: { (res) -> (Void) in
                    if res["code"] as! String == "000000" {
                        showMessage(message: "操作成功")
                        self?.tableView.mj_header.beginRefreshing()
                    }
                })                                
            }else {//重新报价
                
                var j2 = dic.dictionaryObject!
                j2["alias"] = dic["alias"].stringValue
                j2["variety_name"] = dic["variety_name"].stringValue
                j2["num"] = dic["num"].stringValue
                j2["num_unit_text"] = "吨"
                j2["price_unit_text"] = "元/吨"
                j2["depot_name"] = dic["depot_name"].stringValue
                let xieshang = DialogJingjia.showView(frame: (self?.navigationController?.view.bounds)!, data: jsonFormater(data:(j2)))
                xieshang.ob = {[weak self] (d) -> Void in
                    let js = jsonFormater(data: d)
                    NetWorkRequest(.xieshangbiding(fid: dic["fair_id"].stringValue, tid: dic["target_id"].stringValue, price: js["price"].stringValue, content: js["note"].stringValue, delivery_point: js["address"].stringValue), completion: { (res) -> (Void) in
                        xieshang.removeFromSuperview()
                        showMessage(message: res["message"] as! String)
                        if res["code"] as! String == "000000" {
                            self?.tableView.mj_header.beginRefreshing()
                        }
                    })
                    
                    
                }
                self?.navigationController?.view.addSubview(xieshang)
                
                
            }
        }
        cell.commentButtonBlock = {() in
            let vc = R.storyboard.user.commentListViewController()!
            vc.id = dic["id"].stringValue
            self.navigationController?.pushViewController(vc, animated: true)
        }
        return cell
    }
    
}
